// Chrome扩展 - LyricsPinyin 搜索功能
class LyricsPinyinExtension {
    constructor() {
        this.apiUrl = 'https://lyricspinyin.net/api/search';
        this.baseUrl = 'https://lyricspinyin.net';
        this.searchInput = document.getElementById('search-input');
        this.searchButton = document.getElementById('search-button');
        this.loading = document.getElementById('loading');
        this.resultsSection = document.getElementById('results-section');
        this.resultsContainer = document.getElementById('results-container');
        this.resultsCount = document.getElementById('results-count');
        this.noResults = document.getElementById('no-results');
        
        this.init();
    }

    init() {
        // 初始化国际化
        this.initI18n();
        
        // 绑定事件
        this.searchButton.addEventListener('click', () => this.performSearch());
        this.searchInput.addEventListener('keypress', (e) => {
            if (e.key === 'Enter') {
                this.performSearch();
            }
        });

        // 自动聚焦搜索框
        this.searchInput.focus();
    }

    initI18n() {
        // 设置页面标题
        document.title = chrome.i18n.getMessage('extensionName');
        
        // 处理所有带有 data-i18n 属性的元素
        const elements = document.querySelectorAll('[data-i18n]');
        elements.forEach(element => {
            const messageKey = element.getAttribute('data-i18n');
            const message = chrome.i18n.getMessage(messageKey);
            if (message) {
                element.textContent = message;
            }
        });

        // 处理 placeholder 属性
        const placeholderElements = document.querySelectorAll('[data-i18n-placeholder]');
        placeholderElements.forEach(element => {
            const messageKey = element.getAttribute('data-i18n-placeholder');
            const message = chrome.i18n.getMessage(messageKey);
            if (message) {
                element.placeholder = message;
            }
        });
    }

    async performSearch() {
        const keyword = this.searchInput.value.trim();
        
        if (!keyword) {
            this.showError(chrome.i18n.getMessage('enterKeyword'));
            return;
        }

        this.showLoading();
        
        try {
            const response = await fetch(`${this.apiUrl}?keyword=${encodeURIComponent(keyword)}`, {
                method: 'GET',
                headers: {
                    'Accept': 'application/json',
                    'Content-Type': 'application/json'
                }
            });

            if (!response.ok) {
                throw new Error(`HTTP error! status: ${response.status}`);
            }

            const data = await response.json();
            
            // 根据新的数据结构处理结果
            if (data.code === 200 && data.data) {
                // 如果返回的是单个歌曲的完整歌词数据
                if (data.data.title && data.data.lyrics) {
                    this.showLyricsResult(data.data);
                } 
                // 如果返回的是搜索结果列表
                else if (Array.isArray(data.data) && data.data.length > 0) {
                    this.showSearchResults(data.data);
                } 
                else {
                    this.showNoResults();
                }
            } else {
                this.showNoResults();
            }
        } catch (error) {
            console.error('搜索失败:', error);
            this.showError(chrome.i18n.getMessage('errorMessage'));
        }
    }

    showLoading() {
        this.hideAllSections();
        this.loading.classList.remove('hidden');
        this.searchButton.disabled = true;
        this.searchButton.innerHTML = `<span class="spinner"></span><span>${chrome.i18n.getMessage('searching')}</span>`;
    }

    // 显示完整歌词结果
    showLyricsResult(lyricsData) {
        this.hideAllSections();
        this.resetSearchButton();
        
        // 设置结果计数
        this.resultsCount.textContent = chrome.i18n.getMessage('resultsCount', ['1']);
        this.resultsContainer.innerHTML = '';

        // 创建歌词显示元素
        const lyricsElement = this.createLyricsElement(lyricsData);
        this.resultsContainer.appendChild(lyricsElement);

        this.resultsSection.classList.remove('hidden');
        
        // 滚动到结果区域
        this.scrollToResults();
    }

    // 显示搜索结果列表
    showSearchResults(results) {
        this.hideAllSections();
        this.resetSearchButton();
        
        const resultsCountMessage = chrome.i18n.getMessage('resultsCount', [results.length.toString()]);
        this.resultsCount.textContent = resultsCountMessage;
        this.resultsContainer.innerHTML = '';

        results.forEach(result => {
            const resultElement = this.createResultElement(result);
            this.resultsContainer.appendChild(resultElement);
        });

        this.resultsSection.classList.remove('hidden');
        
        // 滚动到结果区域
        this.scrollToResults();
    }

    // 滚动到结果区域
    scrollToResults() {
        // 使用 setTimeout 确保DOM渲染完成
        setTimeout(() => {
            const resultsSection = this.resultsSection;
            if (resultsSection) {
                // 方法1: 使用 scrollIntoView (推荐)
                resultsSection.scrollIntoView({
                    behavior: 'smooth',
                    block: 'start',
                    inline: 'nearest'
                });
                
                // 方法2: 备用方案 - 直接滚动到结果区域顶部
                // const container = document.querySelector('.container');
                // if (container) {
                //     const resultsTop = resultsSection.offsetTop;
                //     container.scrollTo({
                //         top: resultsTop - 20, // 留一点边距
                //         behavior: 'smooth'
                //     });
                // }
            }
        }, 100); // 100ms延迟确保DOM完全渲染
    }

    // 创建歌词显示元素
    createLyricsElement(lyricsData) {
        const lyricsDiv = document.createElement('div');
        lyricsDiv.className = 'lyrics-result';
        
        // 解析歌词数据
        let lyricsContent = '';
        let copyText = ''; // 用于复制的纯文本
        try {
            const lyrics = typeof lyricsData.lyrics === 'string' ? 
                JSON.parse(lyricsData.lyrics) : lyricsData.lyrics;
            
            if (Array.isArray(lyrics)) {
                lyrics.forEach(line => {
                    if (line.original && line.pinyin) {
                        lyricsContent += `
                            <div class="lyrics-line">
                                <div class="lyrics-original">${this.escapeHtml(line.original)}</div>
                                <div class="lyrics-pinyin">${this.escapeHtml(line.pinyin)}</div>
                            </div>
                        `;
                        // 添加到复制文本
                        copyText += `${line.original}\n${line.pinyin}\n\n`;
                    }
                });
            }
        } catch (error) {
            console.error('解析歌词失败:', error);
            lyricsContent = '<div class="lyrics-error">歌词解析失败</div>';
        }
        
        lyricsDiv.innerHTML = `
            <div class="lyrics-header">
                <div class="lyrics-title">${this.escapeHtml(lyricsData.title)}</div>
                <div class="lyrics-artist">${this.escapeHtml(lyricsData.artist)}</div>
                ${lyricsData.album ? `<div class="lyrics-album">${this.escapeHtml(lyricsData.album)}</div>` : ''}
            </div>
            <div class="lyrics-content">
                ${lyricsContent}
            </div>
            <div class="lyrics-footer">
                <button class="copy-button" data-copy-text="${this.escapeHtml(copyText)}">
                    <span class="copy-icon">📋</span>
                    <span class="copy-text">${chrome.i18n.getMessage('copyLyrics')}</span>
                </button>
            </div>
        `;

        // 添加复制功能
        const copyButton = lyricsDiv.querySelector('.copy-button');
        copyButton.addEventListener('click', (e) => {
            e.stopPropagation();
            this.copyToClipboard(copyText, copyButton);
        });

        return lyricsDiv;
    }

    // 复制到剪贴板
    async copyToClipboard(text, button) {
        try {
            // 创建完整的复制文本，包含歌曲信息
            const fullText = text.trim();
            
            // 使用现代 Clipboard API
            if (navigator.clipboard && window.isSecureContext) {
                await navigator.clipboard.writeText(fullText);
                this.showCopySuccess(button);
            } else {
                // 降级方案：使用传统方法
                const textArea = document.createElement('textarea');
                textArea.value = fullText;
                textArea.style.position = 'fixed';
                textArea.style.left = '-999999px';
                textArea.style.top = '-999999px';
                document.body.appendChild(textArea);
                textArea.focus();
                textArea.select();
                
                try {
                    document.execCommand('copy');
                    this.showCopySuccess(button);
                } catch (err) {
                    console.error('复制失败:', err);
                    this.showCopyError(button);
                } finally {
                    document.body.removeChild(textArea);
                }
            }
        } catch (err) {
            console.error('复制失败:', err);
            this.showCopyError(button);
        }
    }

    // 显示复制成功
    showCopySuccess(button) {
        const originalContent = button.innerHTML;
        button.innerHTML = `
            <span class="copy-icon">✅</span>
            <span class="copy-text">${chrome.i18n.getMessage('copySuccess')}</span>
        `;
        button.classList.add('copy-success');
        
        setTimeout(() => {
            button.innerHTML = originalContent;
            button.classList.remove('copy-success');
        }, 2000);
    }

    // 显示复制失败
    showCopyError(button) {
        const originalContent = button.innerHTML;
        button.innerHTML = `
            <span class="copy-icon">❌</span>
            <span class="copy-text">${chrome.i18n.getMessage('copyFailed')}</span>
        `;
        button.classList.add('copy-error');
        
        setTimeout(() => {
            button.innerHTML = originalContent;
            button.classList.remove('copy-error');
        }, 2000);
    }

    showNoResults() {
        this.hideAllSections();
        this.resetSearchButton();
        this.noResults.classList.remove('hidden');
    }

    showError(message) {
        this.hideAllSections();
        this.resetSearchButton();
        
        // 创建错误提示
        const errorDiv = document.createElement('div');
        errorDiv.className = 'no-results';
        errorDiv.innerHTML = `
            <div class="no-results-icon">⚠️</div>
            <p>${message}</p>
            <p class="no-results-tip">${chrome.i18n.getMessage('errorRetry')}</p>
        `;
        
        // 临时显示错误信息
        this.noResults.innerHTML = errorDiv.innerHTML;
        this.noResults.classList.remove('hidden');
        
        // 3秒后恢复原来的无结果提示
        setTimeout(() => {
            this.noResults.innerHTML = `
                <div class="no-results-icon">😔</div>
                <p>${chrome.i18n.getMessage('noResults')}</p>
                <p class="no-results-tip">${chrome.i18n.getMessage('noResultsTip')}</p>
            `;
        }, 3000);
    }

    createResultElement(result) {
        const resultDiv = document.createElement('div');
        resultDiv.className = 'result-item';
        
        // 构建歌词详情页URL
        const lyricsUrl = `${this.baseUrl}/lyrics/${encodeURIComponent(result.title_uri || result.title)}`;
        
        resultDiv.innerHTML = `
            <div class="result-title">${this.escapeHtml(result.title_pinyin || result.title)}</div>
            <div class="result-artist">${this.escapeHtml(result.artist_pinyin || result.artist)}</div>
            <div class="result-stats">
                <div class="result-stats-left">
                    <span>👁️ ${result.views || 0}</span>
                    <span>❤️ ${result.likes || 0}</span>
                </div>
                <a href="${lyricsUrl}" class="result-link" target="_blank">
                    ${chrome.i18n.getMessage('viewLyrics')}
                </a>
            </div>
        `;

        // 点击整个结果项也能打开链接
        resultDiv.addEventListener('click', (e) => {
            if (e.target.tagName !== 'A') {
                chrome.tabs.create({ url: lyricsUrl });
            }
        });

        return resultDiv;
    }

    hideAllSections() {
        this.loading.classList.add('hidden');
        this.resultsSection.classList.add('hidden');
        this.noResults.classList.add('hidden');
    }

    resetSearchButton() {
        this.searchButton.disabled = false;
        this.searchButton.innerHTML = `<span class="search-icon">🔍</span><span>${chrome.i18n.getMessage('searchButton')}</span>`;
    }

    escapeHtml(text) {
        if (!text) return '';
        const div = document.createElement('div');
        div.textContent = text;
        return div.innerHTML;
    }
}

// 页面加载完成后初始化
document.addEventListener('DOMContentLoaded', () => {
    new LyricsPinyinExtension();
});

// 处理外部链接点击
document.addEventListener('click', (e) => {
    if (e.target.tagName === 'A' && e.target.target === '_blank') {
        e.preventDefault();
        chrome.tabs.create({ url: e.target.href });
    }
}); 